<template>
  <el-main>
    <!--    搜索栏-->
    <el-form :model="searchForm" :inline="true" size="default">
      <el-form-item>
        <el-input v-model="searchForm.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchForm.nickName" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" @click="searchBtn">查询</el-button>
        <el-button icon="Close" type="danger" plain @click="resetBtn">重置</el-button>
        <el-button v-if="global.$hasPerm(['sys:user:add'])"  icon="Plus" type="primary" @click="addBtn">新增</el-button>
      </el-form-item>
    </el-form>
    <!--    表格数据-->
    <el-table :height="tableHeight" :data="tableList" size="default">
      <el-table-column prop="nickName" label="姓名"></el-table-column>
      <el-table-column prop="sex" label="性别">
        <template #default="scope">
          <el-tag v-if="scope.row.sex=='0'" type="primary" size="default" effect="dark">男</el-tag>
          <el-tag v-if="scope.row.sex=='1'" type="danger" size="default" effect="dark">女</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="username" label="账户"></el-table-column>
      <el-table-column v-if="global.$hasPerm(['sys:user:edit','sys:user:reset','sys:user:delete'])"  label="操作" align="center" width="320">
        <template #default="scope">
          <el-button v-if="global.$hasPerm(['sys:user:edit'])"  icon="Edit" size="default" type="primary" @click="editBtn(scope.row)">编辑</el-button>
          <el-button v-if="global.$hasPerm(['sys:user:reset'])"  icon="Setting" size="default" type="warning" @click="resetPasswordBtn(scope.row.userId)">重置密码
          </el-button>
          <el-button v-if="global.$hasPerm(['sys:user:delete'])"  icon="Delete" size="default" type="danger" @click="deleteBtn(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!--    分页-->
    <el-pagination @size-change="sizeChange" @current-change="currentChange"
                   :current-page.sync="searchForm.currentPage"
                   :page-sizes="[10,20,40,80,100]"
                   :page-size="searchForm.pageSize" layout="total, sizes, prev, pager, next, jumper"
                   :total="searchForm.total" background></el-pagination>
    <!--    新增编辑弹框-->
    <SysDialog :title="dialog.title" :visible="dialog.visible" :height="dialog.height" :width="dialog.width"
               @on-close="onClose" @on-confirm="commit">
      <template v-slot:content>
        <el-form :model="addModel" ref="addRef" :rules="rules" label-width="80px" :inline="false"
                 size="default">
          <el-row >
            <el-col :span="12" :offset="0">
              <el-form-item prop="nickName" label="姓名">
                <el-input v-model="addModel.nickName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item prop="sex" label="性别">
                <el-radio-group v-model="addModel.sex">
                  <el-radio :label="'0'">男</el-radio>
                  <el-radio :label="'1'">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item prop="phone" label="电话">
                <el-input v-model="addModel.phone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item prop="email" label="邮箱">
                <el-input v-model="addModel.email"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12" :offset="0">
              <el-form-item prop="username" label="账户">
                <el-input v-model="addModel.username"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item prop="roleId" label="角色">
                <SelectChecked ref="selectRef" :options="options" :bindValue="bindValue"
                               @selected="selected"></SelectChecked>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="tags=='0'">
            <el-col :span="12" :offset="0">
              <el-form-item prop="password" label="密码">
                <el-input type="password" v-model="addModel.password"></el-input>
              </el-form-item>
            </el-col>
          </el-row>


        </el-form>

      </template>

    </SysDialog>
  </el-main>
</template>

<script setup lang="ts">
import {nextTick, onMounted, reactive, ref} from "vue";
import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import {ElMessage, type FormInstance} from "element-plus";
import SelectChecked from "@/components/SelectChecked.vue";
import {getSelectApi} from "@/api/role";
import {addApi, deleteApi, editApi, getListApi, getRoleListApi, resetPassword} from "@/api/user";
import type {UserModel} from "@/api/user/UserModel";
import useInstance from '@/hooks/useInstance';

const {global} = useInstance();
const selectRef = ref()
//查询角色下拉数据
const getSlelect = async () => {
  let res = await getSelectApi()
  if (res && res.code == 200) {
    options.value = res.data
  }

}
//查询表格数据
const tableList = ref([])
const getList = async () => {
  let res = await getListApi(searchForm)
  if (res && res.code == 200) {
    tableList.value = res.data.records
    searchForm.total = res.data.total
  }
}
const tableHeight = ref(0)
onMounted(() => {
  getList()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 240

  })
})

const {dialog, onShow, onClose} = useDialog()
//表单验证ref
const addRef = ref<FormInstance>()
//表单验证规则
const rules = reactive({
  nickName: [
    {required: true, message: '请输入姓名', trigger: ['blur', 'change']},
  ],
  sex: [
    {required: true, message: '请选择性别', trigger: 'change'},
  ],
  phone: [
    {required: true, message: '请输入电话', trigger: ['blur', 'change']},
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: ['blur', 'change']},
  ],
  username: [
    {required: true, message: '请输入账户', trigger: ['blur', 'change']},
  ],
  password: [
    {required: true, message: '请输入密码', trigger: ['blur', 'change']},
  ],
  roleId: [
    {required: true, message: '请选择角色', trigger: ['blur', 'change']},
  ],
})
//下拉框数据
let options = ref([])

//下拉勾选的值
const selected = (value: Array<string | number>) => {
  console.log(value)
  addModel.roleId = value.join(',')
}
//搜索栏绑定对象
const searchForm = reactive({
  phone: '',
  nickName: '',
  currentPage: 1,
  pageSize: 10,
  total: 0
})
//根据用户id查询角色,当前用户拥有的角色id
const bindValue = ref([])
const roleIds = ref('')
const getRoleList = async (userId: string) => {
  let res = await getRoleListApi(userId)
  if (res && res.code == 200) {
    bindValue.value = res.data
    roleIds.value = res.data.join(",")
  }
}
//新增编辑弹框绑定对象
const addModel = reactive({
  userId: '',
  username: '',
  password: '',
  phone: '',
  email: '',
  sex: '',
  nickName: '',
  roleId: ''
})
const tags = ref('')
//新增按钮
const addBtn = () => {

  tags.value = '0'
  dialog.title = '新增角色'
  dialog.height = 320
  onShow()
  //清空下拉数据,重新获取
  options.value = []
  bindValue.value = []
  getSlelect()

  //清空表单数据

  nextTick(() => {
    //清空下拉的数据
    selectRef.value.clear();
  })
  addRef.value?.resetFields()
}
//提交表格用户新增或者更新
const commit = () => {
  console.log('提交表格用户新增或者更新')
  addRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      console.log('表单验证通过')
      let res = null
      if (tags.value == '0') {
        res = await addApi(addModel)

      } else {
        res = await editApi(addModel)
      }
      if (res && res.code == 200) {
        ElMessage.success(res.message)
        onClose()
        getList()
      }
    }
  })
}
const searchBtn = () => {
  getList()
}
const resetBtn = () => {
  searchForm.phone = ''
  searchForm.nickName = ''
  searchForm.currentPage = 1;
  getList()
}
//编辑
const editBtn = async (row: UserModel) => {
  tags.value = '1'
//清空下拉数据,重新获取
  options.value = []
  bindValue.value = []
  await getSlelect()
  //清空表单数据
  await getRoleList(row.userId) //查询角色id
  dialog.title = '编辑角色'
  dialog.height = 320


  onShow()
  nextTick(() => {
    //数据回显
    Object.assign(addModel, row)
    //设置角色id
    addModel.roleId = roleIds.value
    addModel.password = ''
  })

  addRef.value?.resetFields()
}
//删除
const deleteBtn = async (userId: string) => {
  const confirm = await global.$myconfirm('确定删除该数据吗?')
  if (confirm) {
    let res = await deleteApi(userId);
    console.log(res);
    if (res && res.code == 200) {
      ElMessage.success(res.message)
      getList();
    }
  }
}
//重置密码
const resetPasswordBtn = async (userId: string) => {
  const confirm = await global.$myconfirm('确定重置密码吗?，重置之后密码默认【666666】')
  if (confirm) {
    let res = await resetPassword({userId: userId});
    console.log(res);
    if (res && res.code == 200) {
      ElMessage.success(res.message)
      getList();
    }
  }
}
//分页相关
//分页容量改变
const sizeChange = (val: number) => {
  searchForm.pageSize = val;
  getList();
}
//当前页改变
const currentChange = (val: number) => {
  searchForm.currentPage = val;
  getList();
}
</script>

<style scoped></style>